<template>
  <div class="my-violations-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>我的违法记录</h3>
          <el-button type="primary" size="small" @click="refreshData">刷新</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="违法类型">
            <el-select v-model="searchForm.type" placeholder="全部类型" clearable>
              <el-option label="行人闯红灯" :value="5" />
              <el-option label="车辆闯红灯" :value="4" />
              <el-option label="车辆压线" :value="3" />
              <el-option label="未按导向行驶" :value="2" />
              <el-option label="超速" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
              <el-option label="未处理" value="0" />
              <el-option label="已处理" value="1" />
              <el-option label="申诉中" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="violationList"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="记录ID" width="80" />
        <el-table-column prop="violationType" label="违法类型">
          <template #default="scope">
            <el-tag :type="getViolationTypeTag(scope.row.violationType)">
              {{ getViolationTypeName(scope.row.violationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" />
        <el-table-column prop="violationTime" label="时间" width="180" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看详情</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="handleAppeal(scope.row)"
              :disabled="scope.row.status !== '0'"
            >申诉</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="违法记录详情"
      width="50%"
    >
      <div v-if="currentViolation" class="violation-detail">
        <div class="detail-item">
          <span class="label">违法类型：</span>
          <span>{{ getViolationTypeName(currentViolation.violationType) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">违法地点：</span>
          <span>{{ currentViolation.location }}</span>
        </div>
        <div class="detail-item">
          <span class="label">违法时间：</span>
          <span>{{ currentViolation.violationTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">处理状态：</span>
          <span>{{ getStatusName(currentViolation.status) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">违法描述：</span>
          <span>{{ currentViolation.description }}</span>
        </div>
        <div class="detail-item">
          <span class="label">违法证据：</span>
          <div class="evidence-images">
            <el-image 
              v-for="(img, index) in currentViolation.evidenceImages" 
              :key="index"
              :src="img"
              :preview-src-list="currentViolation.evidenceImages"
              fit="cover"
              class="evidence-image"
            />
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 申诉对话框 -->
    <el-dialog
      v-model="appealDialogVisible"
      title="提交申诉"
      width="50%"
    >
      <el-form :model="appealForm" label-width="100px" :rules="appealRules" ref="appealFormRef">
        <el-form-item label="申诉理由" prop="reason">
          <el-input 
            v-model="appealForm.reason" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述您的申诉理由..."
          />
        </el-form-item>
        <el-form-item label="上传证据">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appealDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAppealForm">提交申诉</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getViolationPage } from '@/api/violation'
import { submitAppeal } from '@/api/appeal'  // 添加这一行导入

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  dateRange: []
})

// 表格数据
const violationList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const currentViolation = ref(null)

// 申诉对话框
const appealDialogVisible = ref(false)
const appealForm = reactive({
  violationId: '',  // 保持与后端 AppealDTO 一致
  reason: '',
  file: ''  // 修改为与后端 AppealDTO 一致
})
const appealFormRef = ref()
const appealRules = {
  reason: [
    { required: true, message: '请输入申诉理由', trigger: 'blur' },
    { min: 10, message: '申诉理由不能少于10个字符', trigger: 'blur' }
  ]
}

// 获取违法记录列表
const fetchViolationList = async () => {
  loading.value = true
  try {
    // 这里应该调用后端API获取数据
    const response = await getViolationPage({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }, false)  // 明确传入 isAdmin = false
    
    // 处理响应数据
    if (response.code === 200) { // 使用后端定义的成功状态码
      violationList.value = response.data.records
      total.value = response.data.total
      console.log(response.data.records)
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取违法记录失败:', error)
    ElMessage.error('获取违法记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchViolationList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.type = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  fetchViolationList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchViolationList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchViolationList()
}

// 查看详情
const viewDetail = (row) => {
  currentViolation.value = row
  detailDialogVisible.value = true
}

// 处理申诉
const handleAppeal = (row) => {
  appealForm.violationId = row.id  // 修改为正确的字段名
  appealDialogVisible.value = true
}

// 提交申诉
const submitAppealForm = async () => {
  appealFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用后端API提交申诉
        const response = await submitAppeal({
          violationId: appealForm.violationId,
          reason: appealForm.reason,
          file: appealForm.file
           // 修改为与后端 AppealDTO 一致
        })
        
        if (response.code) {
          ElMessage.success('申诉提交成功')
          appealDialogVisible.value = false
          // 重置表单
          appealForm.reason = ''
          appealForm.evidenceFiles = []
          // 刷新列表
          fetchViolationList()
        } else {
          ElMessage.error(response.msg || '申诉提交失败')
        }
      } catch (error) {
        console.error('提交申诉失败:', error)
        ElMessage.error('提交申诉失败')
      }
    }
  })
}

// 处理文件上传
const handleFileChange = (file) => {
  // 将文件转换为后端需要的格式
  // 这里需要根据实际情况调整，可能需要上传文件并获取文件路径
  // 示例：
  const formData = new FormData();
  formData.append('file', file.raw);
  
  // 上传文件并获取路径
  axios.post('/api/upload', formData).then(response => {
    if (appealForm.file) {
      appealForm.file += ',' + response.data;
    } else {
      appealForm.file = response.data;
    }
  }).catch(error => {
    console.error('文件上传失败:', error);
    ElMessage.error('文件上传失败');
  });
}

// 获取违法类型名称
const getViolationTypeName = (type) => {
  const typeMap = {
    1: '超速',           // OVERSPEED
    2: '未按导向行驶',    // TURNWRONG
    3: '车辆压线',       // TOUCHLINE
    4: '车辆闯红灯',     // CARRUNRED
    5: '行人闯红灯'      // RUNRED
  }
  return typeMap[type] || '未知类型'
}

// 获取违法类型标签样式
const getViolationTypeTag = (type) => {
  const tagMap = {
    1: 'warning',     // 超速
    2: 'info',        // 未按导向行驶
    3: 'info',        // 车辆压线
    4: 'danger',      // 车辆闯红灯
    5: 'danger'       // 行人闯红灯
  }
  return tagMap[type] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    '0': '未处理',
    '1': '已处理',
    '2': '申诉中'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const tagMap = {
    '0': 'info',
    '1': 'success',
    '2': 'warning'
  }
  return tagMap[status] || ''
}

onMounted(() => {
  fetchViolationList()
})
</script>

<style scoped>
.my-violations-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.violation-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-item .label {
  font-weight: bold;
  width: 100px;
}

.evidence-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.evidence-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}
</style>